package com.mumu.xiaodu

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.mumu.xiaodu.databinding.ActivityHistoryBinding

class HistoryActivity : FragmentActivity() {
    
    private lateinit var binding: ActivityHistoryBinding
    private lateinit var historyAdapter: HistoryAdapter
    private lateinit var historyManager: HistoryManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        historyManager = HistoryManager(this)
        initViews()
        loadHistory()
    }
    
    private fun initViews() {
        historyAdapter = HistoryAdapter { historyItem ->
            openWebsite(historyItem.url)
        }
        
        binding.rvHistory.layoutManager = LinearLayoutManager(this)
        binding.rvHistory.adapter = historyAdapter
        
        binding.btnBack.setOnClickListener {
            finish()
        }
        
        binding.btnClearHistory.setOnClickListener {
            clearHistory()
        }
    }
    
    private fun loadHistory() {
        val history = historyManager.getAllHistory()
        historyAdapter.updateHistory(history)
        
        if (history.isEmpty()) {
            binding.tvEmptyMessage.visibility = android.view.View.VISIBLE
            binding.rvHistory.visibility = android.view.View.GONE
        } else {
            binding.tvEmptyMessage.visibility = android.view.View.GONE
            binding.rvHistory.visibility = android.view.View.VISIBLE
        }
    }
    
    private fun openWebsite(url: String) {
        val intent = Intent(this, WebViewActivity::class.java)
        intent.putExtra("url", url)
        startActivity(intent)
    }
    
    private fun clearHistory() {
        historyManager.clearAllHistory()
        loadHistory()
    }
} 